package com.example.myx5tbsstatictestdemo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.cnstrong.webview2.X5WebView
import com.cnstrong.webview2.X5WebViewBuilder
import com.cnstrong.webview2.X5WebViewClient
import com.tencent.smtt.sdk.QbSdk
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.text.SimpleDateFormat
import java.util.*

open class MainActivity : AppCompatActivity() {
    companion object {
        private const val TAG = "MainActivity"
        const val INTENT_KEY_FIRST_IN = "FIRST_IN"
        private const val LOAD_X5_DELAY_TIME: Long = 10 * 1000
        const val MAIN_URL = "file:///android_asset/www/no_network_error.html"
    }

    private var mWebView: X5WebView? = null
    private lateinit var frameLayout: FrameLayout
    private lateinit var ivLoadView: ImageView
    private var hasLoadingX5 = false
    private val mX5LoadHandle = Handler(Looper.myLooper()!!)
    private lateinit var mInitWebViewRunnable: Runnable

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        EventBus.getDefault().register(this)
        frameLayout = findViewById(R.id.fl_webview_container)
        ivLoadView = findViewById(R.id.iv_loading)
        Glide.with(this).asGif().load(R.drawable.load_gif).into(ivLoadView)
        initKotlin()
        mInitWebViewRunnable = Runnable {
            mWebView = createWebViewAndStartBusiness()
        }
        if (QbSdk.canLoadX5(this)) {
            Log.d(TAG, "initData canLoadX5")
            hasLoadingX5 = true
            mWebView = createWebViewAndStartBusiness()
        } else {
//            mWebView = createWebViewAndStartBusiness()

            mX5LoadHandle.postDelayed(mInitWebViewRunnable, LOAD_X5_DELAY_TIME)
        }
    }

    private fun createWebViewAndStartBusiness(): X5WebView {
        val x5WebViewBuilder = object : X5WebViewBuilder(this) {
            override fun configWebViewInstance(webView: X5WebView) {
                super.configWebViewInstance(webView)
                webView.webViewClient = X5WebViewClient(webView, ivLoadView)
            }
        }
        val webView = x5WebViewBuilder.build()
        val params = FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT,
            FrameLayout.LayoutParams.MATCH_PARENT
        )
        frameLayout.addView(webView, params)
        webView.loadUrl(MAIN_URL)
        return webView
    }


    fun initKotlin(){
        GlobalScope.launch {
            print("launch用法")
            Log.d(TAG, "initKotlin: ${setTime()}")
            delay(5000)
            Log.d(TAG, "initKotlin: ${setTime()}")
        }
    }

    fun setTime():Long{
        val current = Calendar.getInstance()
        val calendarSetting = Calendar.getInstance()
        calendarSetting.time = Date( SimpleDateFormat("HH:mm", Locale.ENGLISH).parse("10:05")!!.time)
        val hourSetting = calendarSetting[Calendar.HOUR_OF_DAY]
        val minuteSetting = calendarSetting[Calendar.MINUTE]
        current[Calendar.HOUR_OF_DAY] = hourSetting
        current[Calendar.MINUTE] = minuteSetting
        current[Calendar.SECOND] = 10

        return current.timeInMillis/1000 * 1000
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onCanLoadX5Event(x5CanLoadEvent: X5CanLoadEvent) {
        Log.d(TAG, "onCanLoadX5Event: ${x5CanLoadEvent.progress}")
        if (QbSdk.canLoadX5(this) && !hasLoadingX5) {
            mX5LoadHandle.removeCallbacks(mInitWebViewRunnable)
            mWebView = createWebViewAndStartBusiness()
        }
    }


    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        destroyWebView()
        super.onDestroy()
    }


    private fun destroyWebView() {
        try {
            mWebView?.let { mWebView ->
                val parent = mWebView.parent
                if (parent != null) {
                    (parent as ViewGroup).removeView(mWebView)
                }
                mWebView.stopLoading()
                mWebView.settings.javaScriptEnabled = false
                mWebView.removeAllViewsInLayout()
                mWebView.clearHistory()
                mWebView.removeAllViewsInLayout()
                mWebView.removeAllViews()
                mWebView.destroy()
            }
        } catch (e: Exception) {

        }
    }
}